<template>
  <div>
    <template v-if="!isView">
      <van-loading v-if="loading" type="spinner" color="#1989fa" />
      <div class="banner-image">
        <img v-if="addData.url" :src="addData.url" alt="">
        <div class="banner-context">
          <p class="banner-context-title">{{addData.activityName}}</p>
          <p v-if="activityData.activityMaxUmber" style="font-size:14px;font-weight:normal;padding:0 8px;"><span>活动限定{{activityData.activityMaxUmber}}名</span></p>
          <p class="banner-context-desc" v-html="addData.activityContent"></p>
        </div>
      </div>
      <div class="form-group">
        <label>选择类型<em class="required">*</em></label>
        <div :key="moneyData.length">
          <div class="moneybox"  v-for="item in moneyData" :key="item.id" :class="{'active': item.id == currentMoneyId.id}" @click="chooseItem(item)">
            <div v-html="item.optionContent"></div>
            <div class="ok-choose">√</div>
            <div>{{item.activityMoney}}元</div>
          </div>
        </div>
      </div>
      <div class="form-group">
        <label>姓名<em class="required">*</em></label>
        <div>
          <input :readonly="isView" :class="{'validate-error': validate.name}" v-model="addData.name" class="customer-form" type='text' placeholder='输入姓名' focus/> 
        </div>
      </div>
      <div class="form-group">
        <label>性别<em class="required">*</em></label>
        <div>
          <div id="gender" :class="{'selected': gender && gender !== '选择性别','validate-error': validate.gender}">{{gender}}</div>
        </div>
      </div>
      <div class="form-group">
        <label>手机号<em class="required">*</em></label>
        <div>
          <input :readonly="isView" :class="{'validate-error': validate.iphone}" v-model="addData.iphone" class="customer-form" type='text' placeholder='输入手机号' focus/> 
        </div>
      </div>
      <div class="form-group">
        <label>年龄</label>
        <div>
          <input :readonly="isView" v-model="addData.age" class="customer-form" type='text' placeholder='输入年龄' focus/> 
        </div>
      </div>
      <div class="form-group">
        <label>职业</label>
        <div>
          <input :readonly="isView" v-model="addData.career" class="customer-form" type='text' placeholder='输入职业' focus/> 
        </div>
      </div>
      <div class="form-group">
        <label>所属事业部<em class="required">*</em></label>
        <div>
          <div id="businessDivision" :class="{'selected': businessDivision && businessDivision !== '选择所属事业部','validate-error': validate.businessDivision}">{{businessDivision}}</div>
        </div>
      </div>
      <div class="form-group">
        <label>地区<em class="required">*</em></label>
        <div style="display:flex" :class="{'validate-error': validate.address}">
          <div id="province" :class="{'selected': province && province !== '请选择省份'}">{{province}}</div>
          <div id="city" :class="{'selected': city && city !== '请选择城市'}" :key="province">{{city}}</div>
        </div>
      </div>
      <div class="form-group">
        <label>加盟商级别<em class="required">*</em></label>
        <div>
            <div id="resellerLevel" :class="{'selected': resellerLevel && resellerLevel !== '选择加盟商级别','validate-error': validate.resellerLevel}">{{resellerLevel}}</div>
          <!-- <van-checkbox-group :disabled="isView" v-model="addData.resellerLevel">
            <van-checkbox name="客户">客户</van-checkbox>
            <van-checkbox name="1.0系统-分销">1.0系统-分销</van-checkbox>
            <van-checkbox name="1.0系统-一级">1.0系统-一级</van-checkbox>
            <van-checkbox name="1.0系统-小总代">1.0系统-小总代</van-checkbox>
            <van-checkbox name="1.0系统-大总代">1.0系统-大总代</van-checkbox>
            <van-checkbox name="1.0系统-董事">1.0系统-董事</van-checkbox><br/><br/>
            <van-checkbox name="2.0系统-分销">2.0系统-分销</van-checkbox>
            <van-checkbox name="2.0系统-一级">2.0系统-一级</van-checkbox>
            <van-checkbox name="2.0系统-大总代">2.0系统-大总代</van-checkbox>
            <van-checkbox name="2.0系统-董事">2.0系统-董事</van-checkbox><br/><br/>
            <van-checkbox name="3.0系统-合伙人">3.0系统-合伙人</van-checkbox>
            <van-checkbox name="3.0系统-金牌合伙人">3.0系统-金牌合伙人</van-checkbox>
            <van-checkbox name="3.0系统-钻石合伙人">3.0系统-钻石合伙人</van-checkbox>
            <van-checkbox name="3.0系统-战略合伙人">3.0系统-战略合伙人</van-checkbox>
          </van-checkbox-group> -->
        </div>
      </div>
      <div class="form-group">
        <label>身份证号<em class="required">*</em></label>
        <div>
          <input :readonly="isView" :class="{'validate-error': validate.idNumber}" v-model="addData.idNumber" class="customer-form" type='text' placeholder='输入身份证号' focus/> 
        </div>
      </div>
      <div class="form-group">
        <label>直属上级董事姓名<em class="required">*</em></label>
        <div>
          <input :readonly="isView" :class="{'validate-error': validate.inviteName}" v-model="addData.inviteName" class="customer-form" type='text' placeholder='输入直属上级董事姓名' focus/> 
        </div>
      </div>
      <div class="form-group">
        <label>备注</label>
        <div>
          <textarea :readonly="isView" v-model="addData.remark" class="customer-form" bindblur="bindTextAreaBlur" auto-height placeholder="输入备注"/>
        </div>
      </div>
      <div class="form-group" style="text-align:center">
        <button v-if="!isView && activityData.activityStartTime && activityData.activityDeadline && new Date(activityData.activityStartTime.replace(/-/ig, '/')).getTime() < new Date().getTime() && new Date(activityData.activityDeadline.replace(/-/ig, '/')).getTime() > new Date().getTime()" class="btn" plain type="primary" :disabled="isSubmit" @click="submitFn">确认报名<span style="font-size:12px">(报名费用￥{{currentMoneyId.activityMoney || 0}}元)</span></button>
        <button v-if="addData.isPay === '已支付' && activityData.activityDeadline && new Date(activityData.activityDeadline.replace(/-/ig, '/')).getTime() > new Date().getTime()" class="btn" plain type="primary" @click="updatePayStatus('退款中')">申请退款</button>
        <button v-if="addData.isPay === '退款中'" class="btn" plain type="info" disabled>退款审核中...</button>
      </div>
    </template>
    <template v-else>
      <div class="success-info" :style="{backgroundImage: 'url(' +addData.urlBack+ ')'}">
        <div class="success-info-wrapper">
          <div class="success-info-title">{{addData.activityName }}</div>
          <div><img style="width:100px;height:100px;display:block;margin: 15px auto;" :src="weixinData.headImgUrl" alt=""></div>
          <div class="success-info-name">恭喜{{addData.name }}报名成功</div>
          
          <!-- <div class="success-info-foot">
            <button v-if="addData.isPay === '已支付' && activityData.activityDeadline && new Date(activityData.activityDeadline.replace(/-/ig, '/')).getTime() > new Date().getTime()" class="btn" plain type="primary" @click="updatePayStatus('退款中')">申请退款</button>
            <button v-if="addData.isPay === '退款中'" class="btn" plain type="info" disabled>退款审核中...</button>
          </div> -->
        </div>
        <vue-qr :size="150" :margin="12" class="codeQr success-info-qrcode" :text="shareurl  + '?id=' + this.addData.activityId" ></vue-qr>
      </div>
    </template>
  </div>
</template>

<script>
import VueQr from 'vue-qr'
import MobileSelect from 'mobile-select'
import cityData from './city'
import { Toast, Loading } from 'vant';
export default {
    data() {
        return {
            currentMoneyId:{},
            shareurl: location.origin,
            activityData: {},
            loading: false,
            province: '请选择省份',
            city: '请选择城市',
            gender: '选择性别',
            businessDivision: '选择所属事业部',
            resellerLevel:'选择加盟商级别',
            addData:{
                activityContent: '',
                activityName: '',
                resellerLevel: '',
                name:'',
                gender: '',
                iphone:'',
                businessDivision:'',
                idNumber:'',
                inviteName:'',
                address: ''
            },
            valiedateArr:['activityName','resellerLevel','name','gender','iphone','businessDivision','idNumber','inviteName','address',],
            validate:{
                resellerLevel: false,
                name:false,
                gender: false,
                iphone:false,
                businessDivision:false,
                address: false,
                idNumber:false,
                inviteName:false
            },
            errorMessage:{
                iphone: '手机号必须为数字!',
                age: '年龄必须为数字!',
                idNumber: '请输入正确的身份证号码!'
            },
            active: 0,
            list: [],
            objectManger: null,
            cityVisable: false,                                       //遮罩层显示或隐藏
            areaList: [{values: []}, {values: []}],        //自定义数据三级结构
            checkCity: '',
            cityData:[],
            wxPayObject: null,
            isView: false,
            isSubmit: false,
            moneyData:[]
        };
    },
    computed:{
        openId(){
          // return 'oQ2k25tMxkoaZizGT_fHG7A9mBTc'
            return this.$store.state.openId
        },
        id(){
          // return '1409786001196113922'
            return this.$store.state.id
        },
        weixinData(){
          return this.$store.state.weixinData;
        }
    },
    async created(){
        await this.queryActivity();
        this.queryMoneyList();
        await this.queryAccount();
    },
    mounted() {
        const _this = this;
        new MobileSelect({
            trigger: "#gender",
            title: "选择性别",
            wheels: [
                {data: ["男","女"]}
            ],
            callback:function(indexArr, data){
                _this.addData.gender = data[0]
                _this.gender = data[0]
            }
        });
        new MobileSelect({
            trigger: "#businessDivision",
            title: "选择所属事业部",
            wheels: [
                {data: ['金玺事业部',
                    '聚燃事业部',
                    '弘鑫事业部',
                    '事业总部',
                    '慧海事业部',
                    '汇鑫事业部',
                    "77事业部",
                    '众聚事业部',
                    '飞跃事业部',
                    '圣维科技事业部',
                    '聚鑫事业部',
                    '众汇事业部',
                    '风行事业部',
                    '艺锋事业部'
                ]}
            ],
            callback:function(indexArr, data){
                _this.addData.businessDivision = data[0]
                _this.businessDivision = data[0]
            }
        });
        new MobileSelect({
            trigger: "#resellerLevel",
            title: "选择加盟商级别",
            wheels: [
                {data: ['客户',
                  '内部经销商',
                  '董事'
                ]}
            ],
            callback:function(indexArr, data){
                _this.addData.resellerLevel = data[0]
                _this.resellerLevel = data[0]
            }
        });
        new MobileSelect({
            trigger: "#province",
            title: "请选择省份",
            wheels: [
                {data: cityData.p}
            ],
            callback:function(indexArr, data){
                _this.province = data[0]
                _this.addData.province = data[0]
                cityData.p.forEach((item, index) => {
                if(item === data[0]){
                    _this.cityData = cityData.c[index];
                }
                })
                _this.$nextTick(() => {
                    _this.initialCity();
                })
            }
        });
    },
    methods: {
      chooseItem(item){
        this.currentMoneyId = item;
      },
        queryMoneyList(){
          this.currentMoneyId = {};
          this.$axios.get(this.$axios.baseUrl + "/activityOption/list" + '?activityId=' + this.addData.activityId,).then(res => {
              this.moneyData = res.data.data;
          });
        },
        async queryAccount(){
            await this.$axios.get(this.$axios.baseUrl + "/user/detail?openId=" + this.openId + '&activityId=' + this.addData.activityId).then(res => {
                let temp = JSON.parse(JSON.stringify(res.data.data))
                if(res.data.code == 200 && temp && temp.isPay !== '待支付'){
                    this.isView = true;
                }else{
                    this.isView = false;
                }
                if(temp){
                    let tempParams = {
                        ...this.addData,
                        ...temp
                    }
                    this.addData = tempParams;
                    this.province = temp.address.split(',')[0];
                    this.city = temp.address.split(',')[1];
                    this.gender = temp.gender;
                    this.resellerLevel = temp.resellerLevel;
                    this.businessDivision = temp.businessDivision;
                }
            });
        },
        async queryActivity(){
            await this.$axios.get(this.$axios.baseUrl + "/activity/detail?id=" + this.id).then(res => {
                this.activityData = res.data.data;
                this.addData.activityName = res.data.data.activityName;
                this.addData.activityId = res.data.data.id;
                this.addData.activityContent = res.data.data.activityContent;
                this.addData.url = this.$axios.baseUrl + "/images/" +  res.data.data.imageName;
                this.addData.urlBack = this.$axios.baseUrl + "/images/" +  res.data.data.backgroundImageName;
            });
        },
        initialCity(){
            const _this = this;
            _this.city = '请选择城市';
            new MobileSelect({
                trigger: "#city",
                title: "请选择城市",
                wheels: [
                    {data: _this.cityData}
                ],
                callback:function(indexArr, data){
                    _this.city = data[0]
                    _this.addData.city = data[0]
                }
            });
        },
        radioChange(val){
        console.log(val)
        },
        onchange(index) {
        this.list = this[`list${index + 1}`];
        },
        onCancel() {
            this.cityVisable = false;
        },
        //点击确定
        onAreaConfirm(value) {
            if (value[2] && value[2].code) {
                this.checkCity = value[2];
            } else if (value[1] && value[1].code) {
                this.checkCity = value[1];
            } else if (value[0] && value[0].code) {
                this.checkCity = value[0];
            } else {
                this.checkCity = null;
            }
            this.cityVisable = false;
        },
        onAreaChange(picker, values, index) {
            if (index < 2) {
                this.getArea(values[index].code, index + 1);                        //传参 参数为上层选择的地区的code
            }
        },
        async submitFn(){
          if(!this.currentMoneyId.id){
            Toast('请选择类型!');
            return
          }
            let flag = false;
            if(this.province !== '请选择省份' && this.city !== '请选择城市'){
                this.addData.address = `${this.province},${this.city}`
            }
            let params = JSON.parse(JSON.stringify(this.addData));
            Object.keys(params).forEach(key => {
                if(!params[key]){
                    if(this.valiedateArr.includes(key)){
                        this.validate[key] = true;
                        flag = true;
                    }
                }else{
                    if(key === 'iphone' || key === 'age'){
                        if(/^[0-9]*$/.test(params[key]) === false){
                            this.validate[key] = true;
                            flag = true;
                            Toast(this.errorMessage[key]);
                        }else{
                            this.validate[key] = false;
                        }
                    }else{
                        if(key === 'idNumber'){
                            if(/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(params[key]) === false){
                              this.validate[key] = true;
                              flag = true;
                              Toast(this.errorMessage[key]);
                            }else{
                              this.validate[key] = false;
                            }
                        }else{
                            this.validate[key] = false;
                        }
                    }
                }
            })
            if(flag){
                return
            }
            this.loading = true;
            params.openId = this.openId;
            params.activityMoney = this.currentMoneyId.activityMoney;
            params.optionContent = this.currentMoneyId.optionContent;
            let urls = '/user/submit';
            if(params.id){
                urls = '/user/update';
            }
            this.isSubmit = true;
            this.$axios.post(this.$axios.baseUrl + urls, params).then(res => {
                if(res.data.code == 200){
                    this.queryPayId();
                }else{
                    Toast.fail('报名失败');
                    this.isSubmit = false;
                }
                this.loading = false;
            }, (err) => {
                    Toast.fail('报名失败');
                this.loading = false;
                    this.isSubmit = false;
            });
        },
        getRandomStr(len){
            len = len || 32;
            const $chars = 'abcdefghijkmnoprstwxyvz2345678';
            const maxPos = $chars.length;
            let str = '';
        　　for (i = 0; i < len; i++) {
                str += $chars.charAt(Math.floor(Math.random() * maxPos));
        　　}
        　　return str
        },
        onBridgeReady(){
            let _this = this;
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', this.wxPayObject,
                function(res){
                    if(res.err_msg == "get_brand_wcpay_request:ok" ){
                        _this.queryAccount();
                        // _this.updatePayStatus('已支付');
                        _this.isSubmit = false;
                    }else{
                        this.isSubmit = false;
                    }
                }
            ); 
        },
        async queryPayId(){
            await this.$axios.get(this.$axios.baseUrl + "/order/wexinPay?openId=" + this.openId + '&activityMoney=' + this.currentMoneyId.activityMoney.toString() + '&activityId=' + this.addData.activityId).then(res => {
                this.wxPayObject = res.data.data;
                this.updatePayStatus();
                // this.onBridgeReady();
            }, (err) => {
                Toast.fail('获取prepayId失败!');
            });
        },
        updatePayStatus(status){
            this.$axios.get(this.$axios.baseUrl + "/order/weixinpayBack?openId=" + this.openId + "&activityId=" + this.id + '&userPayNumber=' + this.wxPayObject.userPayNumber).then((res) => {
                if(res.data){
                  this.onBridgeReady();
                }else{
                  this.queryPayId();
                }
            });
        }
    },
    components: {
        VueQr
    }
};
</script>

<style>
  .success-info{
    position: absolute;
    top:0;
    bottom:0;
    right:0;
    left:0;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    display: flex;
    justify-content: center;
  }
  .success-info-wrapper{
    width: 80%;
    background: rgba(0, 0, 0, 0.25);
    margin: 0 auto;
    margin-top: 20%;
    padding: 30px 8px;
    border-radius: 5px;
    height: 275px;
  }
  .success-info-title{
    color: #fff;
    font-size: 20px;
    font-weight: 700;
    text-align: center;
    padding: 0 15px;
  }
  .success-info-name{
    margin-top: 20px;
    color: #fff;
    font-size: 20px;
    font-weight: 700;
    text-align: center;
    padding: 0 15px;
  }
  .success-info-qrcode{
    margin: 0 auto;
    display: block !important;
    /* margin-top: 52%; */
    position: absolute;
    bottom: 55px;
  }
  .success-info-foot{
    margin-top: 50px;
  }


  .banner-image{

  }
  .banner-image img{
    width: 100%;
  }
  .banner-context-title{
    font-weight: bold;
    font-size: 15px;  
    margin: 8px;
  }
  .banner-context-desc{
    font-size: 12px;
    margin: 5px 8px;
    line-height: 20px;
  }
  .form-group{
    margin: 18px 0 0 0;
  }
  .form-group>label{
    font-size: 14px;
    display: block;
    margin:0 0 5px 12px;
  }
  .form-group>div .customer-form{
    width: 100%;
    height: 28px;
    border: none;
    padding: 0 8px 0 12px;
    box-sizing: border-box;
  }
  .form-group>div textarea.customer-form{
    width: 100%;
    height: 58px;
    border: none;
    padding: 5px 8px 5px 12px;
  }
  .form-group>div .customer-form::-webkit-input-placeholder{
    font-size: 12px;
    color: #999;
  }
  #objectManger,#gender,#businessDivision,#resellerLevel{
    width: 100%;
    height: 28px;
    border: none;
    padding: 0 12px;
    background: #fff;
    font-size: 12px;
    line-height: 28px;
    color: #999;
  }
  #objectManger.selected,
  #province.selected,
  #city.selected,
  #gender.selected,
  #businessDivision.selected,
  #resellerLevel.selected{
    color: #000;
    font-size: 14px;
    padding: 0 8px 0 12px;
  }
  #objectManger::after{
    content: ' ';
    display: inline-block;
    width: 16px;
    height: 16px; 
  }
  #province{
    width: 50%;
    height: 28px;
    border: none;
    padding: 0 12px;
    background: #fff;
    font-size: 12px;
    line-height: 28px;
    color: #999;
  }
  #city{
    width: 50%;
    height: 28px;
    border: none;
    padding: 0 12px;
    background: #fff;
    font-size: 12px;
    line-height: 28px;
    color: #999;
  }
  .btn{
    color: #FFFFFF;
    background-color: #1AAD19;
    position: relative;
    display: block;
    margin-left: auto;
    margin-right: auto;
    padding-left: 14px;
    padding-right: 14px;
    box-sizing: border-box;
    font-size: 18px;
    text-align: center;
    text-decoration: none;
    line-height: 2.55555556;
    border-radius: 5px;
    -webkit-tap-highlight-color: transparent;
    width: 90%;
    margin-top: 15px;
    margin-bottom: 15px;
    border: none;
  }
  .van-checkbox{
    width: 50%;
  }
  .van-checkbox,.van-checkbox__icon,.van-icon{
    display: inline-block;
    font-size: 14px;
  }
  .required{
    color: red;
    size: 12px;
  }
  .validate-error{
    border: 1px solid red !important;
  }
  .moneybox{
    padding: 2px 5px;
    background: #fff;
    position: relative;
  }
  .moneybox div:first-child{
    font-size: 14px;
    margin: 8px;
    line-height: 20px;
  }
  .moneybox div:last-child{
    font-size: 14px;
    padding: 10px;
    color: #f59115;
    border-bottom: 1px solid #ddd;
    padding-top: 4px;
  }
  .ok-choose{
    color: #fff;
    position: absolute;
    right: 20px;
    bottom: 15px;
    font-size: 20px;
  }
  .moneybox.active .ok-choose{
    color: #f59115;
  }
</style>
